<template>
  <div class="chapterExercise">
    <Header></Header>
    <div class="main">
      <div class="banner">
        <img
            style="width: 100%"
            src="https://img.js.design/assets/img/617766b867e5da8dd2a409b5.png"
            alt=""
        />
      </div>
      <div class="breadcrumb">
        <el-breadcrumb :separator-icon="'ArrowRightBold'">
          <el-breadcrumb-item class="link" @click="toIndex"
          >首页
          </el-breadcrumb-item
          >
          <el-breadcrumb-item class="link" @click="toQuestionBack"
          >我的题库
          </el-breadcrumb-item
          >
          <el-breadcrumb-item class="link" @click="toBack">{{
              subject_name
            }}
          </el-breadcrumb-item>
          <el-breadcrumb-item class="link">整卷练习</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div style="align-items: center" v-if="subjects">
        <el-row :gutter="20" style="margin-right: 0">
          <el-col :span="17">
            <el-card class="box-card">
              <template #header>
                <el-row>
                  <el-col :span="6" style="display: flex; align-items: center">
                    <span v-if="active_subject.parent_id">
                                            第{{ active_subject.parent_sort }}-{{ active_subject.sort }}题，{{ active_subject.type_name }}
                                        </span>
                    <span v-else>
                                            第{{ active_subject.sort }}题，{{ active_subject.type_name }}
                                        </span>
                    <!--                    <span>{{-->
                    <!--                      `第${active_idx + 1}题，${active_subject.type_name}`-->
                    <!--                    }}</span>-->
                  </el-col>
                  <el-col :span="18">
                    <div class="card-header">
                      <div>
                        <el-tag
                            v-if="mode == 'train'"
                            class="ml-2"
                            style="margin-right: 20px"
                        >
                          <span style="display: flex; align-items: center"
                          ><img
                              src="../../../assets/tiku/time.png"
                              alt=""
                          />&nbsp;{{
                              source.useTime
                                  ? proxy.$filters.timeFormat(source.useTime)
                                  : proxy.$filters.timeFormat(0)
                            }}</span
                          >
                        </el-tag>
                      </div>
                      <div style="display: flex; align-items: center">
                        <el-button-group>
                          <el-button
                              :type="active_subject.flag ? 'primary' : ''"
                              size="small"
                              @click="active_subject.flag = !active_subject.flag"
                          >
                            <el-icon>
                              <Flag/>
                            </el-icon>
                            &nbsp;{{ active_subject.flag ? " 取消" : "标记" }}
                          </el-button>
                          <el-button
                              @click="addLike(active_subject.topic_id)"
                              size="small"
                              :type="active_subject.is_collect ? 'primary' : ''"
                          >
                            <el-icon>
                              <StarFilled/>
                            </el-icon>&nbsp;收藏
                          </el-button>
                          <el-button size="small" @click="checked"
                          >
                            <el-icon>
                              <View/>
                            </el-icon>&nbsp;解析
                          </el-button
                          >
                        </el-button-group>
                      </div>
                    </div>
                  </el-col>
                </el-row>
              </template>
              <!--              v-if="active_subject && active_subject.parent_id"-->
              <el-button
                  style="margin-right: 15px;margin-bottom: 15px"
                  size="small"
                  v-if="active_subject && active_subject.parent_id"
                  type="primary"
                  @click="isCase = !isCase"
              >查看题目背景
              </el-button
              >
              <Question
                  :subject="active_subject"
                  v-model:user_answer="active_subject.user_answer"
                  :mode="mode"
                  @checked="checked"
              >
              </Question>
              <img class="question-icon" src="../../../assets/tiku/zjlx-icon.png" alt="">
            </el-card>
            <div style="margin-top: 30px">
              <el-button-group>
                <el-button
                    type="primary"
                    @click="pre"
                    :disabled="active_idx <= 0"
                >
                  {{ "< 上一题" }}
                </el-button>
                <el-button
                    type="primary"
                    @click="next"
                    :disabled="active_idx >= subjects.length - 1"
                >
                  {{ "下一题 >" }}
                </el-button>
              </el-button-group>
            </div>
            <!--                        <div v-html="leads[active_subject.parent_id]"></div>-->
          </el-col>
          <el-col :span="7">
            <div class="grid-content bg-purple-dark"/>
            <div class="button-group">
              <div style="display: flex">
                <el-button size="small" plain type="primary" :icon="'Tickets'" style="margin-right: 16px"
                           @click="tableOfRates = !tableOfRates">税率表
                </el-button>
                <el-button
                    size="small"
                    plain
                    type="primary"
                    :icon="'Search'"
                    @click="showCalculator"
                >计算器
                </el-button
                >
              </div>
            </div>
            <div v-if="mode == 'analysis'" class="question_result">
              <div class="card">答题报告</div>
              <div class="demo-progress">
                <el-progress
                    type="dashboard"
                    :stroke-width="3"
                    :width="71"
                    :percentage="80"
                >
                  <template #default="{ percentage }">
                    <span class="percentage-value">{{
                        proxy.$filters.timeFormat(useTime)
                      }}</span>
                    <span class="percentage-label">做题时长</span>
                  </template>
                </el-progress>
                <el-progress
                    type="dashboard"
                    :stroke-width="3"
                    :width="71"
                    :percentage="80"
                >
                  <template #default="{ percentage }">
                    <span class="percentage-value">{{ score }}</span>
                    <span class="percentage-label">客观题得分</span>
                  </template>
                </el-progress>
                <el-progress
                    type="dashboard"
                    :stroke-width="3"
                    :width="71"
                    :percentage="80"
                >
                  <template #default="{ percentage }">
                    <span class="percentage-value">{{ objectiveScore }}</span>
                    <span class="percentage-label">客观题总分</span>
                  </template>
                </el-progress>
              </div>
              <div class="exam_quesion_score">
                <div style="display: flex; justify-content: center">
                  <span class="title"
                  >*自动判分只能判断客观题，主观题不计得分/总分</span
                  >
                </div>
                <div class="table-body">
                  <!-- <table class="table" cellspacing="0">
                                        <tr>
                                            <td>题型</td>
                                            <td>总分（分）</td>
                                            <td>得分（分）</td>
                                        </tr>
                                        <tr v-if="single">
                                            <td>单项选择题</td>
                                            <td>{{single && single.totalScore ? single.totalScore : null}}</td>
                                            <td>{{single && single.score ? single.score : 0}}</td>
                                        </tr>
                                        <tr v-if="multiterm">
                                            <td>多项选择题</td>
                                            <td>{{multiterm && multiterm.totalScore ? multiterm.totalScore : null}}</td>
                                            <td>{{multiterm && multiterm.score ? multiterm.score : 0}}</td>
                                        </tr>
                                        <tr v-if="synthesize">
                                            <td>综合分析题</td>
                                            <td>{{synthesize && synthesize.totalScore ? synthesize.totalScore:null}}</td>
                                            <td>{{synthesize && synthesize.score ? synthesize.score:0}}</td>
                                        </tr>
                                    </table> -->
                  <table class="table_result">
                    <tr>
                      <th>题型</th>
                      <th>总分（分）</th>
                      <th>得分（分）</th>
                    </tr>
                    <tr v-if="single && single.typeCode !=9">
                      <td>{{ question_types.filter(item => item.code == String(single['typeCode']))[0].value }}</td>
                      <td>{{ single && single.totalScore ? single.totalScore : 0 }}</td>
                      <td>{{ single && single.score ? single.score : 0 }}</td>
                    </tr>
                    <tr v-if="multiterm && multiterm.typeCode !=9">
                      <td>{{ question_types.filter(item => item.code == String(multiterm['typeCode']))[0].value }}</td>
                      <td>{{ multiterm && multiterm.totalScore ? multiterm.totalScore : 0 }}</td>
                      <td>{{ multiterm && multiterm.score ? multiterm.score : 0 }}</td>
                    </tr>
                    <tr v-if="synthesize && synthesize.typeCode !=9">
                      <td>{{question_types.filter(item => item.code == String(synthesize['typeCode']))[0].value}}</td>
                      <td>{{synthesize && synthesize.totalScore ? synthesize.totalScore:0}}</td>
                      <td>{{synthesize && synthesize.score ? synthesize.score:0}}</td>
                    </tr>
                  </table>
                </div>
              </div>
            </div>
            <div>
              <Picker
                  :subjects="subjects"
                  v-model:index="active_idx"
                  :height="'300'"
                  :mode="mode"
              >
              </Picker>
            </div>
            <div>
              <el-button
                  v-if="mode == 'train'"
                  type="primary"
                  @click="submitAnswerFun"
                  class="submit-button"
              >交卷并查看结果
              </el-button
              >
            </div>
          </el-col>
        </el-row>
      </div>
      <el-empty
          v-else
          style="height: 560px"
          :image-size="200"
          description="暂无数据"
      />
    </div>
    <TableOfRates v-model="tableOfRates" :img-url="imgUrl"></TableOfRates>
    <Case
        v-show="isCase"
        @anliClose="anliClose"
        :caseContent="
          active_subject && active_subject.parent_id
            ? leads[active_subject.parent_id]
            : ''
        "
    ></Case>
    <Dialog :dialogVisible="dialogVisible" @dialogEnd="dialogEnd"></Dialog>
    <div class="parent" v-if="isCalculator">
      <Vue3DraggableResizable
          :initW="280"
          :minW="220"
          v-model:x="x"
          v-model:y="y"
          v-model:w="w"
          v-model:h="h"
          v-model:active="active"
          :draggable="true"
          :resizable="true"
          @activated="print('activated')"
          @deactivated="print('deactivated')"
          @drag-start="print('drag-start')"
          @resize-start="print('resize-start')"
          @dragging="print('dragging')"
          @resizing="print('resizing')"
          @drag-end="print('drag-end')"
          @resize-end="print('resize-end')"
      >
        <Calculator @closeCalcuator="closeCalcuator"></Calculator>
      </Vue3DraggableResizable>
    </div>
    <staticFooter></staticFooter>
  </div>
</template>

<script>
import TableOfRates from "@/components/TableOfRates";
import Dialog from '@/components/dialog/index'
import Case from "../../../components/Case";
import staticFooter from "../../../components/staticFooter";
import Calculator from "../../../components/calculator/Calculator";
import {
  submit_result,
  submitAnswer,
} from "../../../hock/submit_question/submit_questions";
import SubmitAnswerSheet from "../../../components/submitAnswerSheet/SubmitAnswerSheet";
import goBackHistory from "../../../utils/hook/goBackHistory";
import Question from "../../../components/Question/Question";
import Picker from "../../../components/Picker/Picker";
import comm_chapter from "../../../hock/composables/comm_chapter";

import {Flag} from "@element-plus/icons-vue";
import {ref, watch} from "vue";
import Header from "../../../components/Header";
import {useRoute, useRouter} from "vue-router";
import {
  reactive,
  toRefs,
  onBeforeUnmount,
  getCurrentInstance,
  onMounted,
} from "vue";
import {exerciseMessage, lookExamPaper, taxRateTable} from "../../../api/api";
import source_to_subjects from "../../../hock/public/source_to_subjects";
import {ElMessage, ElMessageBox} from "element-plus";
import {meCollect} from "../../../utils/hook/addLike/meCollect";

export default {
  name: "index",
  setup() {
    let route = useRoute();
    let router = useRouter();
    const {proxy} = getCurrentInstance();
    let data = reactive({
      x: 100,
      y: 100,
      h: 100,
      w: 100,
      active: false,
      isCalculator: false,
      id: null,
      method: null,
      subject_name: "",
      ques_list: [],
      mode: "train",
      single: null, //单项
      multiterm: null, //多项
      synthesize: null, //综合
      useTime: null, //做题时长
      objectiveScore: null, //客观题总分
      score: null, //客观题得分
      isCase: false,
      tableOfRates: false,
      dialogVisible: false,
      question_types: [{code: '1', value: '单项选择题'}, {code: '2', value: '多项选择题'}, {
        code: '3',
        value: '不定项选择题'
      }, {code: '4', value: '判断题'}, {code: '5', value: '填空题'}, {code: '6', value: '简答题'}, {
        code: '7',
        value: '论述题'
      }, {code: '8', value: '案例题'}, {code: '9', value: '综合题'}, {code: '10', value: '平台操作题'}]
    });
    data.id = route.params.id;
    data.method = route.params.method;
    data.subject_name = route.params.subject_name;
    let fraction = route.params.fraction;
    data.mode = fraction == "null" ? "train" : "analysis";
    const active_idx = ref(0);
    const active_subject = ref(null);
    const {source, subjects, leads, question_id} = comm_chapter(data.method, {
      subjectID: Number(data.id),
    });
    if (data.method == "lookExamPaper" && fraction != "null") {
      lookExamPaper({subjectID: Number(data.id)}).then((res) => {
        console.log("整卷练习记录详情", res.data.fractionClassify);
        data.score = getScore(res.data.fractionClassify);
      });
    }
    let setTimer = setInterval(() => {
      try {
        source.value.useTime = source.value.useTime ? source.value.useTime : 0;
        source.value.useTime++;
      } catch (e) {
      }
    }, 1000);

    const closeCalcuator = (param) => {
      data.isCalculator = param;
    }

    let anliClose = () => {
      data.isCase = false;
    };

    let dialogEnd = (params) => {
      data.dialogVisible = params;
      submit();
    }

    let sumbmitResult = (result) => {
      console.log("result", result.res);
      let {useTime, objectiveScore, fractionClassify} = result.res.data;
      data.useTime = useTime;
      data.score = getScore(fractionClassify);
      data.objectiveScore = objectiveScore;
      const subjects_leads = source_to_subjects(result.res.data);
      console.log("subjects_leads", subjects_leads);
      subjects.value = subjects_leads.subjects;
      leads.value = subjects_leads.leads;
      data.mode = "analysis";
      clearInterval(setTimer);
    };
    let getScore = (fractionClassify) => {
      let score = 0;
      for (let i in fractionClassify) {
        score += fractionClassify[i].score
        data.single = fractionClassify[0]
        data.multiterm = fractionClassify[1]
        data.synthesize = fractionClassify[2]
      }
      return score;
    };

    let submit = async () => {
      let answerSheet = {
        state: 1,
        id: source.value.id,
        index: active_idx.value,
        useTime: source.value.useTime,
        answerLogs: answerLogs(),
      };
      let result = await submitAnswer(answerSheet, "examPaperParse");
      sumbmitResult(result);
    }

    let submitAnswerFun = () => {
      ElMessageBox.confirm(
          '童鞋,请您确认是否需要提交试卷',
          '温馨提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            data.dialogVisible = true
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '已取消',
            })
          })
    };
    let answerLogs = () => {
      let answerLogs = [];
      for (let item of subjects.value) {
        if (item.user_answer) {
          answerLogs.push({id: item.id, answer: item.user_answer.split("")});
        }
      }
      return answerLogs;
    };
    watch(active_idx, () => {
      active_subject.value = subjects.value[active_idx.value];
    });
    watch(source, () => {
      active_subject.value = subjects.value[active_idx.value];
      data.mode = source.value["fraction"] != null ? "analysis" : "train";
      if (source.value["fraction"] != null) {
        console.log("source", source.value);
        let {useTime, objectiveScore, fractionClassify} = source.value;
        data.useTime = useTime;
        data.score = getScore(fractionClassify);
        data.objectiveScore = objectiveScore;
      }
    });
    const checked = () => {
      active_subject.value.checked = true;
    };
    const next = () => {
      active_idx.value = (active_idx.value + 1) % subjects.value.length;
    };
    const pre = () => {
      active_idx.value -= 1;
    };
    let closeSubmit = async () => {
      let answerSheet = {
        state: 0,
        id: source.value.id,
        index: active_idx.value,
        useTime: source.value.useTime,
        answerLogs: answerLogs(),
      };
      let result = await submitAnswer(answerSheet, "examPaperParse");
      console.log(result);
      clearInterval(setTimer);
      // window.removeEventListener("beforeunload", () => {});
    };
    // window.addEventListener("beforeunload", closeSubmit);
    let toIndex = () => {
      if (data.mode == "train") {
        ElMessageBox.confirm(
            "童鞋，您的题目还没有交卷哦，确定要退出吗？",
            "温馨提示",
            {
              confirmButtonText: "保存并退出",
              cancelButtonText: "继续做题",
              type: "warning",
            }
        )
            .then(() => {
              closeSubmit();
              router.push({name: "index"});
              let urlParams = goBackHistory.return_history();
              router.push({name: urlParams.name, params: urlParams.params});
            })
            .catch(() => {
            });
      } else {
        router.push({name: "index"});
        let urlParams = goBackHistory.return_history();
        router.push({name: urlParams.name, params: urlParams.params});
      }
    };
    let toQuestionBack = () => {
      if (data.mode == "train") {
        ElMessageBox.confirm(
            "童鞋，您的题目还没有交卷哦，确定要退出吗？",
            "温馨提示",
            {
              confirmButtonText: "保存并退出",
              cancelButtonText: "继续做题",
              type: "warning",
            }
        )
            .then(() => {
              closeSubmit();
              router.push({name: "MyQuestionBank"});
              let urlParams = goBackHistory.return_history();
              router.push({name: urlParams.name, params: urlParams.params});
            })
            .catch(() => {
            });
      } else {
        router.push({name: "MyQuestionBank"});
        let urlParams = goBackHistory.return_history();
        router.push({name: urlParams.name, params: urlParams.params});
      }
    };
    onBeforeUnmount(() => {
      closeSubmit();
    });

    let toBack = () => {
      if (data.mode == "train") {
        ElMessageBox.confirm(
            "童鞋，您的题目还没有交卷哦，确定要退出吗？",
            "温馨提示",
            {
              confirmButtonText: "保存并退出",
              cancelButtonText: "继续做题",
              type: "warning",
            }
        )
            .then(() => {
              closeSubmit();
              let urlParams = goBackHistory.return_history();
              router.push({name: urlParams.name, params: urlParams.params});
            })
            .catch(() => {
            });
      } else {
        let urlParams = goBackHistory.return_history();
        router.push({name: urlParams.name, params: urlParams.params});
      }
    };
    let showCalculator = () => {
      data.isCalculator = !data.isCalculator;
    };
    let print = (val) => {
      console.log(val);
    };

    //添加或取消收藏
    let addLike = (id) => {
      active_subject.value.is_collect = !active_subject.value.is_collect;
      meCollect(id);
    };

    let imgUrl = ref('')
    let getTaxRateTable = () => {
      taxRateTable().then(res => {
        console.log(res)
        imgUrl.value = res.data[0]
      })
    }
    getTaxRateTable();
    return {
      closeCalcuator,
      dialogEnd,
      imgUrl,
      anliClose,
      addLike,
      print,
      showCalculator,
      proxy,
      toIndex,
      toQuestionBack,
      submitAnswerFun,
      sumbmitResult,
      question_id,
      toBack,
      ...toRefs(data),
      active_idx,
      active_subject,
      source,
      subjects,
      checked,
      next,
      pre,
      leads,
    };
  },
  components: {
    TableOfRates,
    Header,
    Question,
    Picker,
    SubmitAnswerSheet,
    Calculator,
    staticFooter,
    Case,
    Dialog
  },
};
</script>

<style>
.button-group .el-button {
  width: 48%;
}
</style>

<style scoped>
.box-card {
  position: relative;
}

.question-icon {
  position: absolute;
  top: 50%;
  right: 0%;
  transform: translate(-10%, -10%);
}

.parent {
  width: 200px;
  height: 200px;
  position: absolute;
  top: 0px;
  right: 200px;
  user-select: none;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.button-group div {
  width: 100%;
}

.exam_quesion_score .table-body {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.exam_quesion_score table tr td {
  text-align: center;
  color: rgba(51, 51, 51, 1);
  font-size: 12px;
  font-weight: 400;
  border: 1px solid rgba(224, 224, 224, 1);
}

.exam_quesion_score {
  background-color: #ffffff;
}

.exam_quesion_score .title {
  color: rgba(153, 153, 153, 1);
  font-size: 12px;
  font-weight: 400;
  line-height: 12px;
  border-bottom: 1px solid rgba(232, 232, 232, 1);
}

.submit-button {
  width: 100%;
}

.percentage-value {
  display: block;
  font-size: 15px;
  color: #409eff;
}

.percentage-label {
  display: block;
  margin-top: 5px;
  font-size: 12px;
}

.demo-progress {
  padding: 10px;
  background-color: white;
  display: flex;
  justify-content: space-around;
}

.question_result {
  margin-bottom: 20px;
}

.question_result .card {
  background: rgba(42, 130, 228, 1);
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  padding: 10px 0;
  text-align: center;
  color: white;
}

.chapterExercise {
  background-color: rgba(247, 247, 247, 1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.link {
  cursor: pointer;
}

.link:hover {
  color: skyblue;
}

.main {
  margin: 0 auto;
  width: 75rem;
  margin-bottom: 60px;
}

.breadcrumb {
  height: 40px;
  display: flex;
  align-items: center;
}

.banner {
  width: 100%;
  height: 15rem;
  position: relative;
  overflow: hidden;
}

.banner > img {
  position: absolute;
  top: -100%;
}

.table_result table {
  width: 100%;
  margin: 15px 0;
  border: 1;
}

.table_result th {
  background-color: #00a5ff;
  color: #ffffff;
}

.table_result,
.table_result th,
.table_result td {
  font-size: 0.85em;
  text-align: center;
  padding: 5px 15px;
  border-collapse: collapse;
}

.table_result th,
.table_result td {
  border: 1px solid #6dcbfe;
  border-width: 1px 0 1px 0;
}

.table_result tr {
  border: 1px solid #6dcbfe;
}
</style>
